package com.wukang.photovoltaicinspectionpictures.base

import android.app.Dialog
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.viewbinding.ViewBinding
import kotlinx.coroutines.launch
import me.jessyan.autosize.internal.CustomAdapt

/**
 * 基础[AppCompatActivity]
 * @param VB [AppCompatActivity]布局对应的[ViewBinding]实现类
 * @author wukang
 */
abstract class BaseActivity<VB : ViewBinding, VM : BaseViewModel> : AppCompatActivity(), CustomAdapt {
    protected val dialogDispose = mutableListOf<Dialog>()

    /**
     * 等比例适配以高度为准
     */
    override fun isBaseOnWidth(): Boolean = false

    /**
     * 以manifest配置为准
     */
    override fun getSizeInDp(): Float = 0f

    /**
     * activity[ViewBinding]实例
     */
    lateinit var mBinding: VB
        private set

    /**
     * activity[ViewModel]实例
     */
    lateinit var mModel: VM
        private set

    /**
     * 初始化[ViewBinding]实现类
     */
    abstract fun initViewBinding(): VB

    /**
     * 初始化[ViewModel]实现类
     */
    abstract fun initViewModel(): VM

    /**
     * 初始化视图
     */
    abstract fun VB.initView()

    /**
     * 初始化界面
     */
    abstract fun initActivity()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 布局拓展全屏
        enableEdgeToEdge()
        // 初始化viewbinding
        mBinding = initViewBinding()
        setContentView(mBinding.root)
        // 初始化viewmodel
        mModel = initViewModel()
        mModel.setActivity(this)
        // 设置布局不在状态栏和导航栏中
        ViewCompat.setOnApplyWindowInsetsListener(mBinding.root) { v, insets ->
            insets.apply {
                getInsets(WindowInsetsCompat.Type.systemBars()).also {
                    v.setPadding(it.left, it.top, it.right, it.bottom)
                }
            }
        }
        // 其他初始化
        mBinding.initView()
        initActivity()

        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.DESTROYED) {
                // 在界面销毁时取消dialog，防止内存泄露
                dialogDispose.forEach {
                    if (it.isShowing) {
                        it.cancel()
                    }
                }
            }
        }
    }
}